<template>
  <div style="padding:16px;">
    <el-card shadow="never">
      <template #header>
        <div style="display:flex; align-items:center; justify-content:space-between;">
          <span style="font-size:16px; font-weight:600;">订单管理</span>
          <div>
            <el-button type="primary" @click="openDialog" style="margin-right:8px;">新建订单</el-button>
            <el-button v-role="'ROLE_ADMIN'" type="primary" @click="exportXlsx" style="margin-left:8px;">导出Excel</el-button>
          </div>
        </div>
      </template>

      <el-form :inline="true" @submit.prevent>
        <el-form-item label="状态">
          <el-input v-model="status" placeholder="如 未开始/进行中/已结束" clearable @clear="load" />
        </el-form-item>
        <el-form-item label="客户">
          <el-input v-model="customerQuery" placeholder="按客户名称查询" clearable @clear="load" />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker v-model="startDate" type="date" placeholder="开始" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker v-model="endDate" type="date" placeholder="结束" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="load">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="items" stripe border style="width:100%" empty-text="暂无数据">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="customerId" label="客户" min-width="160">
          <template #default="{ row }">{{ customerName(row.customerId) }}</template>
        </el-table-column>
        <el-table-column prop="materialId" label="材料" min-width="220">
          <template #default="{ row }">{{ materialsText(row) }}</template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" min-width="180">
          <template #default="{ row }">{{ quantitiesText(row) }}</template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始" width="120">
          <template #default="{ row }">{{ formatDate(row.startDate) }}</template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束" width="120">
          <template #default="{ row }">{{ formatDate(row.endDate) }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="statusLabelAndType(row.status).type">{{ statusLabelAndType(row.status).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="总价" width="120" />
      </el-table>

      <div style="display:flex; align-items:center; justify-content:space-between; margin-top:16px;">
        <span style="font-size:12px; color:#666;">共 {{ total }} 条</span>
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="size"
          background
          layout="prev, pager, next, sizes, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="load"
          @current-change="load"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" title="新建订单" width="600px">
      <el-form ref="formRef" :model="form" label-width="100px" @submit.prevent>
        <el-form-item label="客户" prop="customerId" :rules="[{ required: true, message: '请选择客户' }]">
          <el-select v-model="form.customerId" placeholder="选择客户" filterable style="width:100%">
            <el-option v-for="c in customers" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="材料" prop="materialIds" :rules="[{ required: true, message: '请选择材料' }]">
          <el-select v-model="form.materialIds" multiple placeholder="选择材料" filterable style="width:100%" @change="onMaterialIdsChange">
            <el-option v-for="m in selectMaterials" :key="m.id" :label="m.name" :value="m.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="数量明细">
          <div style="display:grid; grid-template-columns: 1fr 160px; gap:8px; width:100%">
            <template v-for="mid in form.materialIds" :key="mid">
              <div>{{ materialName(mid) }}</div>
              <el-input-number v-model="form.materialQuantities[mid]" :min="1" controls-position="right" style="width:100%" />
            </template>
          </div>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate" :rules="[{ required: true, message: '请选择开始日期' }]">
          <el-date-picker v-model="form.startDate" type="date" value-format="YYYY-MM-DD" style="width:100%" />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate" :rules="[{ required: true, message: '请选择结束日期' }]">
          <el-date-picker v-model="form.endDate" type="date" value-format="YYYY-MM-DD" style="width:100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status" :rules="[{ required: true, message: '请选择状态' }]">
          <el-select v-model="form.status" placeholder="选择状态" style="width:100%">
            <el-option label="未开始" :value="'2'" />
            <el-option label="进行中" :value="'1'" />
            <el-option label="已结束" :value="'0'" />
          </el-select>
        </el-form-item>
        <el-form-item label="预估总价">
          <div>¥ {{ previewTotal }}</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="create">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { http } from '../api/http'
import type { PageResult, Order } from '../types'

const items = ref<Order[]>([])
const total = ref(0)
const status = ref('')
const customerQuery = ref('')
const startDate = ref('')
const endDate = ref('')
const error = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const form = ref<any>({ customerId: 1, materialIds: [], materialQuantities: {}, startDate: '', endDate: '', status: 'OPEN' })
const page = ref(1)
const size = ref(20)
const customers = ref<any[]>([])
const materials = ref<any[]>([])
const selectMaterials = computed(() => materials.value.filter((m:any) => m.active))

async function load() {
  const res = await http.get<PageResult<Order>>('/api/orders', { params: { page: page.value, size: size.value, status: status.value || undefined, startDate: startDate.value || undefined, endDate: endDate.value || undefined, customerName: customerQuery.value || undefined } })
  items.value = res.data.items
  total.value = res.data.total
}
onMounted(async () => {
  await load()
  const cs = await http.get('/api/customers', { params: { page: 1, size: 1000 } })
  customers.value = cs.data.items || []
  const ms = await http.get('/api/materials', { params: { page: 1, size: 1000 } })
  materials.value = ms.data.items || []
})
function openDialog() {
  form.value = { customerId: 1, materialIds: [], materialQuantities: {}, startDate: '', endDate: '', status: '2' }
  error.value = ''
  dialogVisible.value = true
}
async function create() {
  error.value = ''
  try {
    await formRef.value.validate()
    if (!form.value.customerId || !form.value.materialIds?.length || !form.value.startDate || !form.value.endDate) {
      throw new Error('请完整填写客户、材料、数量与日期')
    }
    const items = form.value.materialIds
      .map((mid: number) => ({ materialId: mid, quantity: Number(form.value.materialQuantities[mid] || 0) }))
      .filter((it: any) => it.quantity && it.quantity > 0)
    const payload = { customerId: form.value.customerId, startDate: form.value.startDate, endDate: form.value.endDate, status: form.value.status, items }
    await http.post('/api/orders', payload)
    await load()
    ElMessage.success('订单创建成功')
    dialogVisible.value = false
  } catch (e: any) {
    error.value = e?.response?.data?.message || e?.message || '创建失败'
    ElMessage.error(error.value)
  }
}
function downloadBlob(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)
}
async function exportXlsx() {
  const res = await http.get('/api/orders/export/xlsx', { params: { status: status.value || undefined, startDate: startDate.value || undefined, endDate: endDate.value || undefined, customerName: customerQuery.value || undefined }, responseType: 'blob' })
  downloadBlob(res.data, 'orders.xlsx')
  ElMessage.success('已导出 Excel')
}

const previewTotal = computed(() => {
  const ids: number[] = form.value.materialIds || []
  if (!ids.length || !form.value.startDate || !form.value.endDate) return '-'
  const s = new Date(form.value.startDate).getTime()
  const e = new Date(form.value.endDate).getTime()
  if (isNaN(s) || isNaN(e) || e < s) return '-'
  const days = Math.floor((e - s) / (24*3600*1000)) + 1
  let total = 0
  for (const mid of ids) {
    const m = materials.value.find((x:any) => x.id === mid)
    const q = Number(form.value.materialQuantities[mid] || 0)
    if (m && m.pricePerDay && q > 0) total += Number(m.pricePerDay) * days * q
  }
  return total.toFixed(2)
})

function onMaterialIdsChange(ids: number[]) {
  const mq = form.value.materialQuantities || {}
  for (const id of ids) {
    if (!mq[id]) mq[id] = 1
  }
  for (const key of Object.keys(mq)) {
    const id = Number(key)
    if (!ids.includes(id)) delete mq[id]
  }
  form.value.materialQuantities = { ...mq }
}

function formatDate(s: string) {
  if (!s) return ''
  const i = s.indexOf('T')
  return i > 0 ? s.slice(0, i) : s
}

function customerName(id: number) {
  const c = customers.value.find((x:any) => x.id === id)
  return c ? c.name : ''
}

function materialName(id: number) {
  const m = materials.value.find((x:any) => x.id === id)
  return m ? m.name : ''
}

function materialsText(row: any) {
  const items: any[] = row.items || []
  if (items.length) {
    return items.map(it => materialName(it.materialId)).join('、')
  }
  return materialName(row.materialId)
}

function quantitiesText(row: any) {
  const items: any[] = row.items || []
  if (items.length) {
    return items.map(it => `${materialName(it.materialId)} x${it.quantity || 0}`).join('、')
  }
  return String(row.quantity || 0)
}

function statusLabelAndType(s: any) {
  const code = typeof s === 'number' || /^\d+$/.test(String(s)) ? Number(s) : null
  if (code !== null) {
    const map: Record<number, { label: string; type: 'info'|'warning'|'success'|'danger' }> = {
      0: { label: '已结束', type: 'success' },
      1: { label: '进行中', type: 'warning' },
      2: { label: '未开始', type: 'info' }
    }
    return map[code] || { label: String(s), type: 'info' }
  }
  const str = String(s).toUpperCase()
  const mapStr: Record<string, { label: string; type: 'info'|'warning'|'success'|'danger' }> = {
    OPEN: { label: '未开始', type: 'info' },
    IN_PROGRESS: { label: '进行中', type: 'warning' },
    COMPLETED: { label: '已结束', type: 'success' }
  }
  return mapStr[str] || { label: String(s), type: 'info' }
}
</script>